/*
 *  Human.cpp
 *  lab3
 *
 *  Created by Fredrik Gustafsson on 11/17/10.
 *  Copyright 2010 Kungliga Tekniska Högskolan. All rights reserved.
 *
 */

#include "Human.h"
#include <algorithm>

using namespace wok2;

Human::~Human() {
	std::vector<Item*>::const_iterator item_it;
	for (item_it = h_items.begin(); item_it!=h_items.end(); item_it++) {
		Item* item = *item_it;
#ifdef DEBUG_DEALLOC
		std::cout << "\t*DBG* Deallocating:" << item->name << std::endl;
#endif
		delete item;
	}
}

std::string Human::type() const{
	return "human";
}

void Human::fight(Actor& enemy){
	std::cout << name << " attemts to stab you..." << std::endl;
	usleep(1000000);
	if (rand()%2==0) {
		std::cout << "But misses!" <<std::endl;
		usleep(1000000);
	} else {
		int damage = gen_damage(100, 50);
		std::cout << enemy.name <<" lose " << damage << " hp." << std::endl;
		usleep(1000000);
		enemy.health-=damage;
	}
}
void Human::talk_to() const {
	std::cout << say_string << std::endl;
}

std::ostream& Human::write_nongeneric(std::ostream& os) const {
	os << say_string << std::endl;
	return os;
}

bool Human::key_to_environment(Environment* env) {
	std::vector<Item*>::iterator it;
	for (it=h_items.begin(); it!=h_items.end(); it++) {
		if ((*it)->type().compare("key")==0)
			if (((Key*)(*it))->opens == env) {
				h_items.erase(it);
				return true;
			}
	}
	return false;
}

void Human::push_item(Item* it) {
	h_items.push_back(it);
}

Item* Human::pop_item(std::string item){
	std::vector<Item*>::iterator it;
	for (it=h_items.begin(); it!=h_items.end(); it++) {
		if (item.compare((*it)->name) == 0) {
			Item* ret = *it;
			h_items.erase(it);
			return ret;
		}
	}
	return NULL;
}
Item* Human::peek_item(std::string item) const {
	std::vector<Item*>::const_iterator it;
	for (it=h_items.begin(); it!=h_items.end(); it++) {
		if (item.compare((*it)->name) == 0) {
			Item* ret = *it;
			return ret;
		}
	}
	return NULL;
}

void Human::print_inventory() const {
	std::cout << "Items in your inventory are:" << std::endl;
	std::vector<Item*>::const_iterator it;
	for (it=h_items.begin(); it!=h_items.end(); it++)
		std::cout << (*it)->name << "(" << (*it)->description << ")" << std::endl;
}

void Human::write_inventory(std::ostream& os) const {
	std::vector<Item*>::const_iterator it;
	for (it=h_items.begin(); it!=h_items.end(); it++) {
		os << "@item" << std::endl
		<< (*it)->name << std::endl
		<< (*it)->description << std::endl << std::endl;
		
		os << "@inventory" << std::endl
		<< name << std::endl
		<< (*it)->name << std::endl << std::endl;
	}
}